#coding: utf-8
from invenio.search_engine import perform_request_search, print_record
from invenio.bibconvert_python_engine import Record
import os
import re
from invenio.websubmit_config import InvenioWebSubmitFunctionStop

def Get_Record_Extract_Subject(parameters, curdir, form, user_info=None):
	recid = ""
	if os.path.exists(os.path.join(curdir, "RECID")):
		recid = open(os.path.join(curdir, "RECID"), "r").read().strip()
	if re.match("\s*nusl-\d+\s*", recid):
		recid = re.search("nusl-(\d+)", recid).group(1)
	try:
		recid = int(recid)
		global sysno
		sysno = recid
	except:
		raise InvenioWebSubmitFunctionStop("Neplatne cislo zaznamu. Spravný zapis je 'nusl-[cislo]' napr. 'nusl-123'")
	marcrec = print_record(recid, format="xm")
	if not marcrec:
		raise InvenioWebSubmitFunctionStop("Zaznam s cislem nusl-%d nebyl nalezen" % recid)
	sn = open(os.path.join(curdir, "SN"), "w")
	sn.write(str(recid))
	sn.close()
	recobj = Record()
	recobj.parse(marcrec)
	pshFile = open(os.path.join(curdir, "psh.key"), "w")
	othersFile = open(os.path.join(curdir, "otherSubjects"), "w") 
	for subject in recobj.get_fields("650", "", "7"):
		stype = subject.get_subfields("2")
		if not stype:
			stype = ""
		else:
			stype = stype[0].value
		val = subject.get_subfields("a")[0].value
		if stype == "PSH":
			pshFile.write("".join((val, "\n")))
		else:
			othersFile.write("".join((val, "---", stype, "\n")))
	pshFile.close()
	othersFile.close()
	return ""
	
if __name__ == "__main__":
	Get_Record_Extract_Subject("", "/root/reindextest/", "")
    

